import asyncio
import os

import pygame

from data.level_data import LevelData
from domain.base import test_colleague_willingness, test_colleague_want_job, format_response, normal_response, \
    relationship_change, colleague_get_intent, get_task_name, colleague_ask_job_is_agree, colleague_response, \
    colleague_give_job_agree, format_response_tones
from shared_variables import CONFIG, SCREEN


class ColleagueTalkScene:
    def __init__(self, screen, level_data: LevelData):
        self.background_color = (0, 0, 0)  # 纯黑背景色
        self.font_size = 20
        self.font_color = (255, 255, 255)  # 白色字体颜色
        self.left_margin = 20
        self.right_margin = 20
        self.top_margin = 20
        self.bottom_margin = 20
        self.max_text_width = 30
        self.max_text_height = CONFIG['screen']['height'] - self.top_margin - self.bottom_margin
        self.screen = screen
        self.level_data = level_data
        self.max_displayed_lines = 5  # 屏幕上最多显示的对话行数
        self.dialogues = []
        self.current_dialogue_index = 0
        self.loop = asyncio.get_event_loop()
        self.talk_task: asyncio.Task = None
        self.finished = False

    def load_assets(self):
        # 在这里加载其他必要的资源
        print("进入了这个页面了吧？")
        boss = self.level_data.get_boss()
        boss_name = boss['name'].values[0]
        conversation = {'avatar': os.path.join(os.curdir, 'assets/head', f'{boss_name}.png'), 'name': boss_name,
                        'content': f"我是老板{boss_name}。同事们正在激烈battle，请耐心等待。"}
        self.dialogues.append(conversation)
        self.talk_task = asyncio.ensure_future(self.talk_situation(self.level_data))

    def handle_events(self, event):
        if self.finished:
            return "settle_project"  # 或者任何其他的结束信号

    def update(self):
        if self.talk_task is not None and not self.talk_task.done():
            # 只处理已经准备好的结果
            try:
                self.loop.run_until_complete(asyncio.wait([self.talk_task], timeout=0))
            except asyncio.TimeoutError as e:
                print(f"出现意外了 {e}")

    def draw(self):
        self.screen.fill(self.background_color)
        start_index = max(0, len(self.dialogues) - self.max_displayed_lines)
        end_index = len(self.dialogues)

        for index in range(start_index, end_index):
            current_dialogue = self.dialogues[index]
            text = current_dialogue['content']
            avatar = pygame.image.load(current_dialogue['avatar'])
            name = current_dialogue['name']
            avatar_rect = avatar.get_rect()

            if index % 2 == 0:
                # 绘制左边的对话内容
                avatar_rect.topleft = (
                    self.left_margin, self.top_margin + index * (avatar_rect.height + self.top_margin))

                name_text = pygame.font.SysFont("方正粗黑宋简体", self.font_size).render(name, True, self.font_color)
                name_rect = name_text.get_rect()
                name_rect.topleft = (
                    self.left_margin + avatar_rect.width + self.left_margin,
                    self.top_margin + index * (avatar_rect.height + self.top_margin))

                text_lines = self.wrap_text(text, self.max_text_width)  # 根据新的换行规则进行包装
                text_y = self.top_margin + index * (avatar_rect.height + self.top_margin) + self.font_size

                self.screen.blit(avatar, avatar_rect)
                self.screen.blit(name_text, name_rect)

                for line in text_lines:
                    text_surface = pygame.font.SysFont("方正粗黑宋简体", self.font_size).render(line, True,
                                                                                                self.font_color)
                    text_rect = text_surface.get_rect()
                    text_rect.topleft = (self.left_margin + avatar_rect.width + self.left_margin, text_y)
                    self.screen.blit(text_surface, text_rect)
                    text_y += self.font_size
            else:
                # 绘制右边的对话内容
                avatar_rect.topright = (
                    CONFIG['screen']['width'] - self.right_margin,
                    self.top_margin + index * (avatar_rect.height + self.top_margin))
                name_text = pygame.font.SysFont("方正粗黑宋简体", self.font_size).render(name, True, self.font_color)
                name_rect = name_text.get_rect()
                name_rect.topright = (
                    CONFIG['screen']['width'] - self.right_margin - avatar_rect.width - self.right_margin,
                    self.top_margin + index * (avatar_rect.height + self.top_margin))

                text_lines = self.wrap_text(text, self.max_text_width)  # 根据新的换行规则进行包装
                text_y = self.top_margin + index * (avatar_rect.height + self.top_margin) + self.font_size

                self.screen.blit(avatar, avatar_rect)
                self.screen.blit(name_text, name_rect)

                for line in text_lines:
                    text_surface = pygame.font.SysFont("方正粗黑宋简体", self.font_size).render(line, True,
                                                                                                self.font_color)
                    text_rect = text_surface.get_rect()
                    text_rect.topright = (CONFIG['screen']['width'] - self.right_margin - 100, text_y)
                    self.screen.blit(text_surface, text_rect)
                    text_y += self.font_size

    def wrap_text(self, text, max_chars):
        lines = []
        while text:
            line = text[:max_chars]
            text = text[max_chars:]
            lines.append(line)
        return lines

    async def talk_situation(self, level: LevelData):
        print("进入了这个函数的")
        ask_name = await asyncio.to_thread(test_colleague_willingness, level)

        if ask_name['name'] != 'unknown':
            job_want = await asyncio.to_thread(test_colleague_want_job, level, ask_name['name'])

            if job_want == 'unknown':
                return

            temp_task_owner = level.get_task_people()
            task_owner = temp_task_owner[temp_task_owner['name_task'] == job_want['task_name']]['name_people'].values[0]

            data = level.prepare_data_between_colleagues(ask_name['name'], task_owner)

            first_ask = await asyncio.to_thread(format_response_tones, ask_name['name'],
                                                f"我想要你的任务 {job_want['task_name']},可以给我么？ 因为{job_want['reason']}",
                                                "")
            self.dialogues.append({'avatar': data['avatar_me'], 'name': data['my_name'],
                                   'content': f"对{data['colleague_name']}说:{first_ask}"})

            iteration = 0
            while True:
                dialogs = '\n'.join([f"{dialog['name']}: {dialog['content']}" for dialog in self.dialogues])
                is_accept, response = await asyncio.to_thread(self.get_colleague_response, data, dialogs)
                self.dialogues.append(
                    {'avatar': data['avatar_colleague'], 'name': data['colleague_name'],
                     'content': f"对{data['my_name']}说:{response}"})
                dialogs = '\n'.join([f"{dialog['name']}: {dialog['content']}" for dialog in self.dialogues])
                if is_accept == '拒绝':
                    iteration += 1
                    if is_accept == '接受' or iteration >= 2:
                        self.finished = True
                        await asyncio.sleep(3)
                        return
                    response = await asyncio.to_thread(format_response, ask_name['name'],
                                                       f"你最好了，{job_want['task_name']}就给我吧。求求了。",
                                                       dialogs)
                else:
                    response = await asyncio.to_thread(normal_response, ask_name['name'], dialogs)

                self.dialogues.append({'avatar': data['avatar_me'], 'name': data['my_name'],
                                       'content': f"对{data['colleague_name']}说:{response}"})
                if is_accept == '接受' or iteration >= 2:
                    self.finished = True
                    await asyncio.sleep(3)
                    return

        self.finished = True

    def get_colleague_response(self, data, dialogs):
        is_accept = ''
        # 如果是第二轮运行，则判断关系是否发生变化
        relationship_update = relationship_change(data['colleague_name'], data['my_name'], data['relationship'],
                                                  dialogs)
        # 更新关系，如果有变化
        if relationship_update['is_change_relationship'] != 'unknown':
            data['relationship'] = relationship_update['new_relationship']
            self.level_data.update_relationship(data['colleague_name'], data['my_name'],
                                                relationship_update['new_relationship'])
            print(f"新的关系：{relationship_update['new_relationship']}")
        # 解析意图
        intent = colleague_get_intent(data['my_name'], data['colleague_name'], dialogs)

        print(intent)
        if intent['intent'] == '要你的任务':
            task_name = get_task_name(dialogs)['task_name']
            current_financial_status, future_financial_status = self.level_data.predict_finance(data)
            agree_result = colleague_ask_job_is_agree(data['colleague_name'], data['my_name'], data['relationship'],
                                                      task_name, current_financial_status, future_financial_status)
            if agree_result['intent'] == '接受':
                response = colleague_response(agree_result['reason'], task_name, "愿意", data['my_name'],
                                              data['colleague_name'], dialogs)
                self.level_data.reassign_task(task_name, data['my_name'])
                is_accept = '接受'
                # 打印reassign_task之前和之后的数据
            else:
                response = colleague_response(agree_result['reason'], task_name, "拒绝", data['my_name'],
                                              data['colleague_name'], dialogs)
                is_accept = '拒绝'

        elif intent['intent'] == '给你任务':
            task_name = get_task_name(dialogs)['task_name']
            agree_result = colleague_give_job_agree(data['my_name'], data['colleague_name'], data['relationship'],
                                                    task_name)
            if agree_result['intent'] == '接受':
                response = colleague_response(agree_result['reason'], task_name, "愿意", data['my_name'],
                                              data['colleague_name'], dialogs)
                self.level_data.reassign_task(task_name, data['colleague_name'])
                is_accept = '接受'
                # 打印reassign_task之前和之后的数据
            else:
                response = colleague_response(agree_result['reason'], task_name, "拒绝", data['my_name'],
                                              data['colleague_name'], dialogs)
                is_accept = '拒绝'
        else:
            response = normal_response(data['colleague_name'], dialogs)

        return is_accept, response


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((CONFIG['screen']['width'], CONFIG['screen']['height']))
    pygame.display.set_caption('Game Title')

    scene = ColleagueTalkScene(SCREEN, None)

    scene.load_assets()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            else:
                scene.handle_events(event)

        scene.update()

        scene.draw()

        pygame.display.flip()

    pygame.quit()
